﻿using IOP.Models.Message.MQTT;
using IOP.Pulsar.MQTT.Client;
using System;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ClientTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Random random = new Random();
                var mqtt = new MQTTClient().Prod(prod =>
                {
                    prod.OnError((p, e) =>
                    {
                        Console.WriteLine(e.Message);
                        p.Dispose();
                    });
                    prod.OnConnack((c, p) =>
                    {
                        Console.WriteLine(p.ConnectReturnCode.ToString());
                        Task.Run(() =>
                        {
                            while (c.IsConnected)
                            {
                                string data = $"X:{random.Next()};Y:{random.Next()};Z:{random.Next()}";
                                c.SendPublish("/uav", Encoding.UTF8.GetBytes(data), QoSType.QoS0);
                                Thread.Sleep(5000);
                            }
                        });
                    });
                    prod.OnPuback((c, p) =>
                    {
                        Console.WriteLine("Puback");
                    });
                    prod.OnPubrec((c, p) =>
                    {
                        Console.WriteLine("Pubrec");
                    });
                    prod.OnPubcomp((c, p) =>
                    {
                        Console.WriteLine("Pubcomp");
                    });
                    prod.OnPingresp((c, p) =>
                    {
                        Console.WriteLine("Pingresp");
                    });
                });
                
                mqtt.Connect(option =>
                {
                    option.KeepAlive = 50;
                    option.ClientIdentifier = "UAV1";
                    option.UserName = "UAV1";
                    option.WillFlag = true;
                    //option.ServerAddress = IPAddress.Parse("127.0.0.1");
                    option.ServerAddress = IPAddress.Parse("10.0.75.1");
                    option.Port = 2333;
                    option.WillQoS = QoSType.QoS0;
                    option.WillTopic = "/uav";
                    option.WillMessage = Encoding.UTF8.GetBytes($"Client {option.ClientIdentifier} is disconnect");
                    option.KeepAlive = 50;
                });

                while (!mqtt.IsDispose) { }


            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                Console.WriteLine("client is disconnect");
                Console.ReadLine();
            }
        }
    }
}
